package cn.miaopasi.boot.clickhouse.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.json.JSONUtil;
import cn.miaopasi.boot.clickhouse.model.LoginLog;
import cn.miaopasi.boot.clickhouse.model.dto.LoginLogDTO;
import cn.miaopasi.boot.clickhouse.service.ILoginLogService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * 登录日志控制层
 *
 * @author Administrator
 */
@RestController
@RequestMapping("/log/login")
public class LoginLogCtl {

    @Resource
    private ILoginLogService loginLogService;

    @Resource
    private HttpServletRequest request;

    /**
     * 保存日志
     *
     * @param loginLog 日志信息
     */
    @PostMapping("add")
    public SaResult add(@RequestBody LoginLog loginLog) {
        String loginId = StpUtil.getLoginIdAsString();
        loginLog.setId(IdUtil.objectId());
        loginLog.setAppId(loginId);
        loginLogService.save(loginLog);
        return SaResult.ok();
    }

    /**
     * 分页查询指定日期的日志
     *
     * @param loginLog 日志查询条件
     * @return 查询的数据
     */
    @PostMapping("page")
    public SaResult page(@RequestBody LoginLogDTO loginLog) {
        final String loginId = StpUtil.getLoginIdAsString();
        loginLog.setAppId(loginId);
        Page<LoginLog> loginLogPage = loginLogService.page(loginLog);
        return SaResult.data(loginLogPage);
    }

    /**
     * 添加测试数据
     *
     * @param size 数据条数
     */
    @GetMapping("generate/{size}")
    public void generate(@PathVariable("size") Integer size) {
        for (int j = 0; j < size; j++) {
            LoginLog loginLog = LoginLog.builder()
                    .id(IdUtil.objectId())
                    .appId("61bf1bc83d24b8f6765647d7")
                    .loginDateTime(LocalDateTime.now())
                    .ip(NetUtil.ipv4ToLong(ServletUtil.getClientIP(request)))
                    .loginHeader(JSONUtil.toJsonStr(ServletUtil.getHeaderMap(request)))
                    .username("admin")
                    .isSuccess(Boolean.TRUE)
                    .build();
            loginLogService.save(loginLog);
        }
    }
}
